package command
{
	import business.WhoDataDelegate;
	
	import com.adobe.cairngorm.commands.ICommand;
	import com.adobe.cairngorm.control.CairngormEvent;
	
	import event.LoadWhoDataEvent;
	
	import flash.utils.Dictionary;
	
	import model.BabyChartModelLocator;
	import model.WhoDataModelLocator;
	
	import mx.collections.ArrayCollection;
	import mx.collections.IList;
	import mx.rpc.IResponder;
	import mx.rpc.events.ResultEvent;
	
	import vo.WhoDataPoint;

	public class LoadWhoDataCommand implements IResponder, ICommand
	{
		private var whoModel:WhoDataModelLocator = WhoDataModelLocator.getInstance();
		private var babyChartModel:BabyChartModelLocator = BabyChartModelLocator.getInstance();
		private var targetDict:Dictionary;
		private var chartType:String;
		
		public function result(data:Object):void
		{
			var resultEvent:ResultEvent = ResultEvent(data);
			var xml:XML = XML(resultEvent.message.body);
			
			for each (var dataXml:XML in xml.data) {
				var datapoint:WhoDataPoint = new WhoDataPoint(dataXml);
				targetDict[datapoint.day] = datapoint;
			}
			
			setDisplayList();
			babyChartModel.changeChartRange();
		}

		public function execute(event:CairngormEvent):void
		{
			var realEvent:LoadWhoDataEvent = LoadWhoDataEvent(event);
			chartType = realEvent.chartType; 
			var service:String = whoModel.getServiceName(chartType);
			targetDict = whoModel.getDataMap(realEvent.chartType);
			new WhoDataDelegate(this).loadWhoData(service);
		}
		
		private function setDisplayList():void {
			var step:Number = Math.ceil(BabyChartModelLocator.MAXRAGE / BabyChartModelLocator.STEPS);
			var targetList:IList = babyChartModel.getList(chartType);
			if (targetList == null) {
				targetList = new ArrayCollection();
				for (var i:Number = 0; i < BabyChartModelLocator.MAXRAGE; i ++) {
					if ((chartType == WhoDataModelLocator.WFA_BOYS || chartType == WhoDataModelLocator.WFA_GIRLS) && i < 10) {
						targetList.addItem(targetDict[i]);
					} else if ( i % step == 0) {
						targetList.addItem(targetDict[i]);
					} /*else if ( !isNaN(targetDict[i].P75)) {
						targetList.addItem(targetDict[i]);
					} */
				}
				babyChartModel.setWhoList(chartType, targetList);
				babyChartModel.setListToDisplay(chartType);
			}
		}
		
		public function fault(info:Object):void
		{
		}
		
	}
}